package com.destroyer.common.excel.converter;

import cn.hutool.core.util.StrUtil;
import com.alibaba.excel.context.WriteContext;
import com.alibaba.excel.converters.Converter;
import com.alibaba.excel.converters.WriteConverterContext;
import com.alibaba.excel.metadata.GlobalConfiguration;
import com.alibaba.excel.metadata.data.ReadCellData;
import com.alibaba.excel.metadata.data.WriteCellData;
import com.alibaba.excel.metadata.property.ExcelContentProperty;
import org.apache.poi.ss.formula.functions.T;

import java.util.Map;

/**
 * 数据型的转换器
 */
public abstract class MapStrConverter implements Converter<String> {
    public abstract Map<String, String> getMap();

    public String defaultVal() {
        return "";
    }

    @Override
    public String convertToJavaData(ReadCellData<?> cellData, ExcelContentProperty contentProperty, GlobalConfiguration globalConfiguration) throws Exception {
        String cellValue = cellData.getStringValue();
        if (StrUtil.isEmpty(cellValue)) {
            return defaultVal();
        }
        return getMap().getOrDefault(cellValue, defaultVal());
    }


    @Override
    public Class<?> supportJavaTypeKey() {
        // 指定这个转换器支持转换的 Java 类型
        return String.class;
    }

    @Override
    public WriteCellData<?> convertToExcelData(WriteConverterContext<String> context) throws Exception {
        // 获取单元格的值
        String value = context.getValue();
        Map<String, String> map = getMap();
        String data = value;
        for (Map.Entry<String, String> entry : map.entrySet()) {
            if (entry.getValue().equals(value)) {
                data = entry.getKey();
                break;
            }
        }
        return new WriteCellData<>(data); // 返回转换后的 WriteCellData 对象
    }
}
    